import localforage from 'localforage'
const DefaultConfig = {
  description: '测试缓存库',
  // driver: DefaultDriverOrder.slice(),
  name: 'localforage',
  // Default DB size is _JUST UNDER_ 5MB, as it's the highest size
  // we can use without a prompt.
  size: 4980736,
  storeName: 'keyvaluepairs',
  version: 1.0
};
// console.log('@@@@@@@@@@@@@@@@@@@@@@@@@@2222', localforage);
localforage.config(DefaultConfig)

const getDataForKey = ()=>{
  // pro__Login_Userinfo
  let res_ = "project_storage_info"
  const res = JSON.parse(localStorage.getItem('pro__Login_Userinfo')||"{}")
  if(res){
    const {value} = res
    const id = value && value.id || ''
    if(id){
      res_ = `${res_ }_${id}`
    }
  }
  return res_
}

const localStorageKey = getDataForKey();

const dataT = 1000 * 60 * 60 * 24 // 一天的毫秒
/**
 * 用于做数据缓存
 *
 */
class LocalforageHelp {
  cache = {};
  currentData = {};
  constructor(option) {
    if (option) {
      localforage.config(option)
    }
    if (!LocalforageHelp.instance) {
      LocalforageHelp.instance = this;
    }
    return LocalforageHelp.instance;
  }

  async set(key, value, expiredTime = 1) {
    const cache_ =await this.get() || {};
    const tempObj = cache_[key]
    if(tempObj){
      // console.log('set 2 00000000000=====>',key,cache_,tempObj,cache_[key]);
      const {newExpired,expired} = tempObj
      if(!this.check(newExpired,expired)){
        delete cache_[key];
      }else{
        cache_[key].value = value
      }
    }else{
      // console.log('set 0 00000000000=====>',key,cache_,tempObj,cache_[key]);
      const info = {
        value,
        newExpired: Date.now(),
        expired: expiredTime * dataT
      };
      cache_[key] = info;
    }
    localforage.setItem(localStorageKey, cache_);
  }

  get(key) {
    return localforage.getItem(localStorageKey).then(readValue => {
      if (readValue) {
        const {newExpired,expired} = readValue
        if(this.check(newExpired,expired)){
          // console.log('Read 1==: ', key, readValue,readValue[key]&&readValue[key].value);
          if (key) {
            return readValue[key] && readValue[key].value || null
          } else {
            return readValue
          }
        }else{
          this.clearExpired(readValue)
          return null
        }
      } else {
        // resolve(readValue)
        return readValue
      }
    }).catch(function (err) {
      // 当出错时，此处代码运行
      console.log(err);
      // reject(err)
    });

  }
  check(newExpired,expired){
    let res= true
    const temp =  Date.now()
    if(temp - newExpired >= expired){
      res= false
    }
    return res
  }
  // remove(key) {
  //   // 此处可根据实际情况提供全部删除方法，个人感觉有一定风险
  //   if (!key) throw new Error("localStorage 删除操作必须传入对应的 key 值！！！");
  //   this.cache = this.get();
  //   delete this.cache[key];
  //   localStorage.setItem(localStorageKey, JSON.stringify(this.cache));
  // }

  async clearExpired(dataList) {
    const cache_ = dataList || await this.get();
    if (!cache_ || !Object.keys(cache_).length) return;
    for (const key in cache_) {
      if (cache_[key].expired < Date.now() - cache_[key].newExpired) {
        delete cache_[key];
      }
    }
    localforage.setItem(localStorageKey, cache_);
  }
}

export default (option) => {
  return new LocalforageHelp(option)
}
